package com.joyance.springmvc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.joyance.springmvc.util.json.JsonUtils;
import com.joyance.springmvc.vo.Person;
import com.joyance.springmvc.vo.PersonList;

@Controller
@RequestMapping("/simple")
public class SimpleAction {

    /**
     * 最基本的接参数及显示（转发）
     * 
     * @return
     */
    @RequestMapping("/helloWorld")
    public ModelAndView helloWorld(String name, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user_name", name);
        modelAndView.setViewName("views/simple");
        return modelAndView;
    }


    /**
     * 模型驱动保存对象
     * 
     * @return
     */
    @RequestMapping("/savePerson")
    public ModelAndView savePerson(Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("person", person);
        modelAndView.setViewName("views/person");
        return modelAndView;
    }


    /**
     * 模型驱动批量保存对象
     * 
     * @return
     */
    @RequestMapping(value = "/savePersons", method = RequestMethod.POST)
    public ModelAndView savePersons(PersonList person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("persons", person);
        modelAndView.setViewName("views/persons");
        return modelAndView;
    }


    /**
     * 重定向
     * 
     * @return
     */
    @RequestMapping(value = "/redirect")
    public ModelAndView redirect(String name) {
        return new ModelAndView("redirect:/simple/helloWorld.do?name=" + name);
    }


    /**
     * ajax请求
     * 
     * @return
     */
    @RequestMapping(value = "/ajaxSubmitObject", method = RequestMethod.GET)
    public @ResponseBody String ajaxSubmitObject(Person person) {
        return JsonUtils.writeObject(person);
    }


    /**
     * 上传文件
     * 
     * @return
     */
    @RequestMapping("/upload")
    public ModelAndView upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();

        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("fileUrl", request.getContextPath() + "/upload/" + fileName);
        modelAndView.setViewName("views/showImage");
        return modelAndView;
    }


    /**
     * 下载文件
     * 
     * @return
     */
    @RequestMapping("/download")
    public String download(String fileName, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        String encodeName = null;
        try {
            encodeName = new String(fileName.split("\\.")[0].getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;charset=UTF-8;fileName=" + encodeName + "." + fileName.split("\\.")[1]);
        try {
            String path = request.getSession().getServletContext().getRealPath("upload");
            InputStream inputStream = new FileInputStream(new File(path + File.separator + fileName));
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping("/velocityTools")
    public String velocityTools(HttpServletRequest request) {
        String number = request.getParameter("number");
        String date = request.getParameter("date");
        Date dateTime = null;
        if (!StringUtils.isEmpty(date)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                dateTime = sdf.parse(date);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (dateTime == null) {
            dateTime = new Date();
        }
        request.setAttribute("number1", number);
        request.setAttribute("date", dateTime);
        return "views/velocityTools";
    }


    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse("2016-03-11 00:00:02");
            System.out.println(date);

            System.out.println(sdf.format(date));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
